// 本地测试
var url = "/sockjs/ws";
// 远程测试
// var url = "ws://180.101.146.240:9081/ws";
var url = "ws://180.101.146.240:9081/ws";
var webSocket = null;
var term = null;

/**
 * socket
 * @type {WebSocket}
 */
// 本地测试
// webSocket = new SockJS(url);
// 远程测试
webSocket = new WebSocket(url);

webSocket.onopen = onOpen;
webSocket.onmessage = onMessage;
webSocket.onerror = onError;
webSocket.onclose = onClose;

function onOpen(event) {
    initTerm();
    bindTerm();
    sendConnMessage("lim", "rap2-mysql-2792910790-90ssj", "mysql");

}

function onMessage(event) {
    term.write(event.data);
}

function onError() {
}

function onClose() {
}

function sendConnMessage(namespace, pod, container) {
    var msg = {};
    msg.type = "1";
    msg.namespace = namespace;
    msg.pod = pod;
    msg.container = container;
    doSend(JSON.stringify(msg));
}

function sendCmdMessage(cmd) {
    var msg = {};
    msg.type = "2";
    msg.cmd = cmd;
    doSend(JSON.stringify(msg));
}

function doSend(msg) {
    console.log(webSocket.readyState);
    if (webSocket.readyState == SockJS.OPEN) {
        webSocket.send(msg);
    } else {
        alert("连接失败!");
    }
}


function disconnect() {
    if (webSocket != null) {
        webSocket.close();
        webSocket = null;
    }
}

function reconnect() {
    if (webSocket != null) {
        webSocket.close();
        webSocket = null;
    }

    webSocket = new SockJS(url);

    webSocket.onopen = onOpen;
    webSocket.onmessage = onMessage;
    webSocket.onerror = onError;
    webSocket.onclose = onClose;
}

/**
 * term
 */
function initTerm() {
    term = new Terminal();
    term.open(document.getElementById('terminal'), {
        focus: true
    });
    term.writeln("welcome...!")
}

function bindTerm() {
    term.on('data', function (data) {
        console.log(data);
        sendCmdMessage(data)
    });
}



